package com.ruoyi.system.util;

import com.ruoyi.system.domain.MinioProp;
import io.minio.*;
import io.minio.errors.*;
import io.minio.messages.Bucket;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;
import java.io.IOException;

import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.UUID;

@Component
public class MinioUtil {


    private static final String[] IMAGE_TYPE=new String[]{".bmp",".jpg",".jpeg",".png",".gif",".mp3",".mp4",".mkv",".docx"};
    @Autowired
    private MinioClient minioClient;
    @Autowired
    private MinioProp minioProp;

    private static final String BUCKET_PREFIX = "images";

    private static final String MONTH_FORMAT = "yyyy-MM";

    private String lastYearBucket = "";
    private String lastMonthBucket = "";

    public String minioUpload(MultipartFile file) throws InsufficientDataException, ErrorResponseException, NoSuchAlgorithmException, IOException, InvalidKeyException, InternalException, ServerException, InvalidResponseException, XmlParserException {
        String returnUrl = "";
        boolean isLegal = false;
        for (String type : IMAGE_TYPE) {
            if (file.getOriginalFilename().toLowerCase().endsWith(type)) {
                isLegal = true;
                break;
            }
        }
        if (!isLegal) {
            return "格式不正确";
        }

        String originalFilename = file.getOriginalFilename();
        String fileType = originalFilename.substring(originalFilename.lastIndexOf("."));
        String newFileName = UUID.randomUUID().toString() + fileType;

        String bucketName = createBucket();

        try {
            String policyJson = "{\"Version\":\"2012-10-17\",\"Statement\":[{\"Effect\":\"Allow\",\"Principal\":\"*\",\"Action\":[\"s3:GetObject\"],\"Resource\":[\"arn:aws:s3:::" + bucketName + "/*\"]}]}";
            minioClient.setBucketPolicy(SetBucketPolicyArgs.builder().bucket(bucketName).config(policyJson).build());
            ObjectWriteResponse response = minioClient.putObject(
                    PutObjectArgs.builder()
                            .bucket(bucketName)
                            .object(newFileName)
                            .stream(file.getInputStream(), file.getSize(), -1)
                            .contentType(file.getContentType())
                            .build()
            );
            if (response!=null){
                 return minioProp.getEndpoint() + "/" + response.bucket() + "/" + response.object();

            }

        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
    private String createBucket() throws  NoSuchAlgorithmException, InsufficientDataException, IOException, InvalidKeyException,ErrorResponseException, InternalException, ServerException, InvalidResponseException, XmlParserException {
        String monthBucket = BUCKET_PREFIX + new SimpleDateFormat(MONTH_FORMAT).format(new Date());

        List<Bucket> buckets = listBuckets();
        boolean monthBucketExists = false;

        for (Bucket bucket : buckets) {
            if (bucket.name().equals(monthBucket)) {
                monthBucketExists = true;
            }
        }
        if (!monthBucketExists) {
            minioClient.makeBucket(MakeBucketArgs.builder().bucket(monthBucket).build());
        }

        return monthBucket;
    }

    public List<Bucket> listBuckets() throws  NoSuchAlgorithmException, InsufficientDataException, IOException, InvalidKeyException, ErrorResponseException, InternalException, ServerException, InvalidResponseException, XmlParserException {
        return minioClient.listBuckets();
    }
}
